package com.greenzebras.geocache;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.widget.Toast;

import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.greenzebras.geocache.constant.GeocacheConstants;
import com.readystatesoftware.mapviewballoons.BalloonItemizedOverlay;

public class GeocacheItemizedOverlay extends BalloonItemizedOverlay<OverlayItem> {

	ArrayList<OverlayItem> _overlays = new ArrayList<OverlayItem>();
	Context _context;

	public GeocacheItemizedOverlay(Context context, Drawable drawable, MapView mapView) {
		super(boundCenterBottom(drawable), mapView);
		populate();
		_context = context;
	}

	@Override
	protected OverlayItem createItem(int i) {
		return _overlays.get(i);
	}

	@Override
	public int size() {
		return _overlays.size();
	}

	public void addOverlay(OverlayItem overlay) {
		_overlays.add(overlay);
		populate();
	}

	@Override
	protected boolean onBalloonTap(int index, OverlayItem item) {
		Double lat = (double) (item.getPoint().getLatitudeE6() / GeocacheConstants.LOCATION_COORD_TO_GEOPOINT_COORD_MULTIPLIER);
		Double lng = (double) (item.getPoint().getLongitudeE6() / GeocacheConstants.LOCATION_COORD_TO_GEOPOINT_COORD_MULTIPLIER);
		launchNavigation(lat, lng);

		return true;
	}

	private boolean canHandleIntent(Context context, Intent intent) {
		PackageManager packageManager = context.getPackageManager();
		List<ResolveInfo> activities = packageManager.queryIntentActivities(
				intent, PackageManager.MATCH_DEFAULT_ONLY);
		return activities.size() > 0;
	}

	private void launchNavigation(Double latitude, Double longitude) {
		String uri = "google.navigation:ll=%f,%f";
		Intent navIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String
				.format(uri, latitude, longitude)));

		if (canHandleIntent(_context, navIntent)) {
			_context.startActivity(navIntent);
		} else {
			Toast.makeText(_context, "Please install google navigation",
					Toast.LENGTH_LONG).show();
		}
	}
}
